﻿using Feifansoft.Core.Common.AppSetting;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Feifansoft.Core.Authentication
{
    public class JwtService : IJwtService
    {
        private readonly IConfiguration _iConfiguration;
        public JwtService(IConfiguration iConfiguration) {
            _iConfiguration = iConfiguration;
        }

        #region 获取Token
        /// <summary>
        /// 生成token
        /// </summary>
        /// <param name="claims"></param>
        /// <returns></returns>
        public string GetJwtToken(Claim[] claims)
        {
            try
            {
                // 生成 ToKen
                var appSetting = _iConfiguration.GetSection(nameof(AppSetting)).Get<AppSetting>();
                var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(appSetting.Jwt.SecurityKey));
                var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                var tokenOptions = new JwtSecurityToken(
                    issuer: appSetting.Jwt.Issuer,
                    audience: appSetting.Jwt.Audience,
                    claims: claims,
                    expires: DateTime.Now.AddMinutes(Convert.ToInt32(appSetting.Jwt.ExpireMinutes)),
                    signingCredentials: signinCredentials
                );

                return new JwtSecurityTokenHandler().WriteToken(tokenOptions);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion

        #region 生成 Token
        /// <summary>
        /// 生成 Token
        /// </summary>
        /// <param name="claims"></param>
        /// <returns></returns>
        private string CreateToken(IEnumerable<Claim> claims)
        {
            var appSetting = _iConfiguration.GetSection(nameof(AppSetting)).Get<AppSetting>();
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(appSetting.Jwt.SecurityKey));
            var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

            var tokenOptions = new JwtSecurityToken(
                issuer: appSetting.Jwt.Issuer,
                audience: appSetting.Jwt.Audience,
                claims: claims,
                expires: DateTime.Now.AddMinutes(Convert.ToInt32(appSetting.Jwt.ExpireMinutes)),
                signingCredentials: signinCredentials
            );

            return new JwtSecurityTokenHandler().WriteToken(tokenOptions);
        }
        #endregion
    }
}
